<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p>计算属性：一个用来做计算的属性</p>
    <p>依赖缓存，当依赖的数据没有变化时，会将计算结果缓存起来，方便下次使用。</p>
    <p>计算属性可以看做是data中的一个数据；实现计算属性时记得return！！！</p>
    <table border="1">
      <thead>
        <tr>
          <th>商品名称</th>
          <th>商品价格</th>
          <th>商品数量</th>
          <th>商品小计</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(phone,index) in goodsList">
          <td>{{phone.name}}</td>
          <td>{{phone.price}}</td>
          <td>{{phone.num}}</td>
          <td>{{phone.price * phone.num}}</td>
        </tr>
        <tr>
          <td colspan="2">总计</td>
          <td>{{totalNum}}件</td>
          <td>{{totalPrice}}元</td>
        </tr>
      </tbody>
    </table>
    <input type="text" v-model.number="a">
    <input type="text" v-model.number="b">
    <p>a+b={{c}}</p>
  </div>
  <script src="../vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        goodsList: [
          {name: 'iphone', num: 5, price: 5999},
          {name: 'huawei', num: 15, price: 6999},
          {name: 'xiaomi', num: 10, price: 5899},
          {name: 'vivo', num: 12, price: 4599},
        ],
        a: 1,
        b: 1,
      },
      computed: {
        c:{
          get() {
            console.log('计算属性被调用');
            return this.a + this.b
          },
          set() {
            console.log('计算属性被赋值');
          }
        },
        totalNum() {
          console.log('computed');
          let num = 0;
          this.goodsList.forEach(item => {
            num += item.num
          });
          return num;
        },
        totalPrice() {
          let num = 0;
          this.goodsList.forEach(item => {
            num += item.num * item.price
          });
          return num;
        }
      },
      methods: {
        totalNumFn() {
          console.log('methods');
          let num = 0;
          this.goodsList.forEach(item => {
            num += item.num
          });
          return num;
        },
        totalPriceFn() {
          let num = 0;
          this.goodsList.forEach(item => {
            num += item.num * item.price
          });
          return num;
        }
      },
    })
  </script>
</body>
</html>